import axios from "axios";
import store from "@/store/index.js";
import { Toast } from "vant";
Toast.allowMultiple();

//全局默认配置
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const instance = axios.create({
  baseURL: "", // 不要设置基础路径,
  timeout: 30000, // 请求超时时间
  headers: {
    "X-Requested-With": "XMLHttpRequest",
    "content-type": "application/json",
  },
  withCredentials: false,
});
instance.defaults.retry = 3; // 全局的请求次数
instance.defaults.retryDelay = 1000; // 全局的请求的间隙
instance.defaults.headers.post["Content-Type"] =
  "application/json;charset=UTF-8";
instance.defaults.unloading = false; // 默认loading
// 增加重试
const retryConnect = (obj) => {
  let config = obj.config; // 获取错误信息
  if (!config || !config.retry) return Promise.reject(obj);
  config.__retryCount = config.__retryCount || 0;
  if (config.__retryCount >= config.retry) {
    return Promise.reject(obj);
  }
  // 重试次数记录
  config.__retryCount += 1;
  let retryPromise = new Promise(function (resolve) {
    setTimeout(function () {
      resolve();
    }, config.retryDelay || 1);
  });
  // Return the promise in which recalls axios to retry the request
  return retryPromise.then(function () {
    return instance(config);
  });
};
/* 请求拦截器 */
instance.interceptors.request.use(
  (config) => {
    config.cancelToken = source.token;
    const tokenId = store.state.token;

    // 异常之后 config.data 会变成字符串 不需要再次拼接
    if (tokenId) {
      config.headers.Authorization = tokenId;
    }
    return config;
  },
  (error) => {
    return Promise.error(error);
  }
);

/* 响应拦截器 */
instance.interceptors.response.use(
  (response) => {
    if (response.data) {
      if (response.data.code == 401) {
        store.commit("logoutMutation");
        source.cancel();
        try {
          // 原生登录
          console.log('需要实现跳转登录界面');
          this.$router.push('/login');
        } catch (e) {
          console.log(e);
        }
      }
      return Promise.resolve(response.data);
    } else {
      Toast.loading({
        duration: 2000, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        mask: false, // 是否显示遮罩层
        message: "网络连接错误...",
      });
    }
    Toast.clear(); //隐藏loading
  },
  (error) => {
    Toast.clear(); // 隐藏loading
    if (axios.isCancel(error)) {
      return new Promise(() => {});
    } else {
      retryConnect(error);
    }
  }
);
instance.all = axios.all;
instance.spread = axios.spread;
export default instance;
